//
//  LoginViewController.m
//  iRMAP
//
//  Created by Ryan Enguero on 3/27/14.
//  Copyright (c) 2014 engueroryan. All rights reserved.
//

#import "CPDScatterPlotViewController.h"

#import "LoginViewController.h"

#import "UiManager.h"

#import "IIViewDeckController.h"

#import "APIs.h"

#import "PostClass.h"

#import "ParserClass.h"

#import "Json.h"

#import "Parameters.h"

#import "loadingView.h"

//#import "User.h"

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

@interface LoginViewController ()

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    usernameTxt.text = username;
    passwordTxt.text = password;
    
    [self.navigationController.navigationBar setHidden:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
   // scrollView.contentOffset = CGPointMake(0, 0);
}

- (void)viewWillDisappear:(BOOL)animated{

    usernameTxt.text = @"";
    passwordTxt.text = @"";
    

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)loginFunction:(id)sender {
    
    [usernameTxt resignFirstResponder];
    [passwordTxt resignFirstResponder];
    
    
    if (self.view.frame.size.height == 568) {
        
        //[UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
         //                animations:^{
                             scrollView.contentOffset = CGPointMake(0, 0);
                             
          //               }
         //                completion:nil
         //];
        
    }else{
        //[UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
          //               animations:^{
                             scrollView.contentOffset = CGPointMake(0, 0);
                             
           //              }
           //              completion:nil
         
       //  ];
    }

    
    @try {
        
        if([usernameTxt.text isEqualToString:@""] || [passwordTxt.text isEqualToString:@""] ) {
            //            [self alertStatus:@"Please enter both Username and Password" :@"Login Failed!"];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Login Failed!" message:@"Please enter both Username and Password" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            
            [alertView show];
            
        } else {
            
//            activityHolderView.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
//            
//            [self.view addSubview:activityHolderView];
            
            
            NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"loadingView" owner:self options:nil];
            loadingView * loading = [xib objectAtIndex:0];
            
            [loading setFrame:CGRectMake(0, 0, 93, 47)];
            
            if (scrollView.frame.origin.x == 0 && scrollView.frame.origin.y == 0) {
                
                [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
                                 animations:^{
                                     [loading.imgBg setBackgroundColor:[UIColor whiteColor]];
                                     [self.view addSubview:loading];
                                     [self.loginFunctionProp setEnabled:NO];
                                     
                                 }
                                 completion:nil
                 
                 ];
                
                
            }
    
            
            
            
            
            dispatch_async(kBgQueue, ^{
            

            NSDictionary* json = [[PostClass sharedItems] getUsername:usernameTxt.text andGetPassword:passwordTxt.text];

                
            
            NSString *status = [NSString stringWithFormat:@"%@", [[json  objectForKey:@"return"] objectForKey:@"status"]];
            
            if ([status isEqualToString:@"success"]) {
                NSLog(@"Success");
                
                [[ParserClass sharedItems] userDetails:json];
                
                NSLog(@"Parse UserDetails = %@", [[ParserClass sharedItems] userdetails]);
                
                    [loading removeFromSuperview];
                    [self.loginFunctionProp setEnabled:YES];
//                User *user = [[ParserClass sharedItems] userdetails][0];
//                
//
//                
//                NSDictionary* listOfCompaniesJson = [NSJSONSerialization
//                                      JSONObjectWithData:[[PostClass sharedItems] getCompanies:[user sessionID]]
//                                      options:kNilOptions
//                                      error:&error];
//                
//                [[ParserClass sharedItems] listOfCompanies:listOfCompaniesJson];
//                NSLog(@"Parse Company Details = %@", [[ParserClass sharedItems] companyDetails]);

                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [activityHolderView removeFromSuperview];

                IIViewDeckController *deckView = [[UiManager sharedItems] generateControllerStack];
                
                //[self presentViewController:deckView animated:YES completion:nil];
                     self.navigationController.interactivePopGestureRecognizer.enabled = NO;
                    [self.navigationController pushViewController:deckView animated:YES];
                    
                });
                
                
                
            }else if ([status isEqualToString:@"error"]){
                
                NSLog(@"Error");
                dispatch_async(dispatch_get_main_queue(), ^{
                
                [activityHolderView removeFromSuperview];
                [self.loginFunctionProp setEnabled:YES];
                [loading removeFromSuperview];
                
                NSString *errorMsg = [NSString stringWithFormat:@"%@", [[[json  objectForKey:@"return"] objectForKey:@"error"] objectForKey:@"message"]];
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:errorMsg delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                
                [alertView show];
                    });
            }
             });
        }
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        //  [self alertStatus:@"Login Failed." :@"Login Failed!"];
    }
    
}


#pragma mark - TextFieldDelegate

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    if (self.view.frame.size.height == 568) {
        
        [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
                         animations:^{
                             scrollView.contentOffset = CGPointMake(0, 75);
                         }
                         completion:nil
         ];
    }else{
        
        [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
                         animations:^{
                             scrollView.contentOffset = CGPointMake(0, 180);
                         }
                         completion:nil
         ];
    }
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    if (self.view.frame.size.height == 568) {
        
        [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
                         animations:^{
                             scrollView.contentOffset = CGPointMake(0, 0);
                             
                         }
                         completion:nil
         ];
        
    }else{
        [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
                         animations:^{
                             scrollView.contentOffset = CGPointMake(0, 0);
                             
                         }
                         completion:nil
         ];
    }
    
    return YES;
}







@end
